package com.tarena.baking.controller;

import com.tarena.baking.common.enums.UserTypeEnum;
import com.tarena.baking.common.ex.ServiceException;
import com.tarena.baking.mapper.UserMapper;
import com.tarena.baking.pojo.param.UserEditParam;
import com.tarena.baking.pojo.param.UserLoginParam;
import com.tarena.baking.pojo.param.UserParam;
import com.tarena.baking.pojo.entity.User;
import com.tarena.baking.pojo.vo.UserLoginVO;
import com.tarena.baking.response.JsonResult;
import com.tarena.baking.response.StatusCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;


@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("login")
    public JsonResult login(@Valid @RequestBody UserLoginParam userParam) {



        System.out.println("userParam = " + userParam);
        UserLoginVO userVO = userMapper.selectByUserName(userParam.getUserName());
        // 创建Spring Security所需的认证参数
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                userParam.getUserName(), userParam.getPassword());
        // 执行认证，获取结果
        Authentication authenticateResult = authenticationManager.authenticate(authentication);
        // 将认证结果存入到SecurityContext
        SecurityContextHolder.getContext().setAuthentication(authenticateResult);


        return JsonResult.ok(userVO);
    }

    @RequestMapping("reg")
    public JsonResult reg(@Valid @RequestBody UserParam userParam) {
        UserLoginVO userLoginVO = userMapper.selectByUserName(userParam.getUserName());
        if (userLoginVO != null) {
            throw new ServiceException(StatusCode.USER_NAME_ALREADY_EXIST,"用户名已存在");
        }
        User user = new User();
        BeanUtils.copyProperties(userParam, user);
        user.setCreateTime(new Date());
        user.setPassword(passwordEncoder.encode(userParam.getPassword()));
        user.setIsAdmin(UserTypeEnum.USER.getValue());
        userMapper.insert(user);
        return JsonResult.ok();
    }

    @RequestMapping("update")
    public void update(@RequestBody UserEditParam userEditParam) {
        System.out.println("userEditParam = " + userEditParam);
        User user = new User();
        BeanUtils.copyProperties(userEditParam, user);
        userMapper.update(user);
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @GetMapping("getUserList")
    public JsonResult getUserList() {
        return JsonResult.ok(userMapper.getAllUser());
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @RequestMapping("changeAdmin")
    public void changeAdmin(Long id, Integer isAdmin) {
        userMapper.changeAdmin(id, isAdmin);
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @RequestMapping("delete")
    public void delete(Long id) {
        userMapper.deleteById(id);
    }


    @RequestMapping("logout")
    public void logout() {
        SecurityContextHolder.clearContext();
    }

}
